package com.example.smartvillage.cunmin;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.Toast;

import androidx.appcompat.widget.AppCompatToggleButton;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.smartvillage.MainViewModel;
import com.example.smartvillage.R;
import com.example.smartvillage.adapters.ExpandableListAdapter;
import com.example.smartvillage.onenet.MyOneNetApi;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.switchmaterial.SwitchMaterial;
import com.google.gson.JsonArray;

import java.util.Objects;

public class LightControlFragment extends BottomSheetDialogFragment {

    private static final String TAG = "灯光控制";

    MainViewModel model;
    MyOneNetApi myOneNetApi;

    String[] locations = {"客厅","卧室","厨房"};
    String[][] bulbs = {{"灯泡1","灯泡2","灯泡3","灯泡4","灯泡5"},{"灯泡1","灯泡2","灯泡3"},{"灯泡1","灯泡2"}};
    boolean[][] allBulbStates = {{false,false,false,false,false},{false,false,false},{false,false}};
    ExpandableListAdapter lightListAdapter;

    ExpandableListView expandableListView;

    public LightControlFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        model = new ViewModelProvider(requireActivity()).get(MainViewModel.class);
        myOneNetApi = Objects.requireNonNull(model.getMyOneNetApi().getValue());

        //每次进入更新数据
        boolean[] newBulbStates = new boolean[1];
        String ledId = "灯光4控制";
        myOneNetApi.getDataStreams(ledId, response -> {
            if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                JsonArray obj = response.body().get("data").getAsJsonArray();
                newBulbStates[0] = (obj.get(0).getAsJsonObject().get("current_value").getAsInt() == 1);
                Log.d(TAG, "获取的灯光状态" + newBulbStates[0]);
                model.setBulbStates(newBulbStates);
            }
        });

        lightListAdapter = new ExpandableListAdapter(locations, bulbs, allBulbStates, getContext());
        lightListAdapter.setChildClickListener(childClickListener);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_light_control, container, false);

        expandableListView = view.findViewById(R.id.light_list);

        expandableListView.setAdapter(lightListAdapter);

        model.getBulbStates().observe(this, bulbStatesObserver);

        return view;
    }

    Observer<boolean[]> bulbStatesObserver = new Observer<boolean[]>() {
        @Override
        public void onChanged(boolean[] bulbStates) {
            Log.d(TAG, "ModelView的灯光状态"+bulbStates[0]);
            boolean[][] newBulbStates = {{bulbStates[0],false,false,false,false},{false,false,false},{false,false}};
            lightListAdapter.setChildValues(newBulbStates);
            lightListAdapter.notifyDataSetChanged();
        }
    };

    ExpandableListAdapter.ChildClickListener childClickListener = new ExpandableListAdapter.ChildClickListener() {
        @Override
        public void OnChildClick(View view, int groupPosition, int childPosition) {
            Log.d(TAG, "你切换了"+locations[groupPosition]+"中的"+bulbs[groupPosition][childPosition]);

            AppCompatToggleButton clickedButton = (AppCompatToggleButton)view;
            boolean isChecked = clickedButton.isChecked();

            String command;
            Drawable drawable = ContextCompat.getDrawable(requireContext(), R.drawable.ic_round_lightbulb_24);

            if (groupPosition == 0) {
                if (childPosition == 0) {
                    command = "LED41:" + (isChecked?"1":"0");
                    boolean[] states = model.getBulbStates().getValue();

                    myOneNetApi.sendCommand(0, 0, command, response -> {

                        if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                            Toast.makeText(getContext(), "成功创建命令", Toast.LENGTH_SHORT).show();

                            //更新ViewModel中的数据
                            states[childPosition] = isChecked;
                            model.setBulbStates(states);
                        }
                        else if (response.body().get("errno").getAsInt() == 10) {
                            clickedButton.setChecked(!isChecked);
                            Toast.makeText(getContext(), "设备不在线", Toast.LENGTH_SHORT).show();
                        }
                        //可以控制的灯更新视图
                        if (clickedButton.isChecked()) {
                            drawable.setTint(getResources().getColor(R.color.white));
                            clickedButton.setTextColor(getResources().getColor(R.color.white));
                        }
                        else {
                            drawable.setTint(getResources().getColor(R.color.darker_gray));
                            clickedButton.setTextColor(getResources().getColor(R.color.darker_gray));
                        }
                        clickedButton.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable,null,null,null);
                    });
                }
            }
            //所有灯更新视图
            if (clickedButton.isChecked()) {
                drawable.setTint(getResources().getColor(R.color.white));
                clickedButton.setTextColor(getResources().getColor(R.color.white));
            }
            else {
                drawable.setTint(getResources().getColor(R.color.darker_gray));
                clickedButton.setTextColor(getResources().getColor(R.color.darker_gray));
            }
            clickedButton.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable,null,null,null);
        }
    };
}